package com.example.star.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.api_service.ApiStar;
import com.example.star.entity.Star;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageUploadUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

// 明星发布页 Activity
public class StarActivity extends AppCompatActivity {

    private ImageButton backButton;
    private ImageView imageView;
    private EditText nameEditText;
    private EditText ageEditText;
    private EditText birthDateEditText;
    private EditText birthPlaceEditText;
    private EditText nationalityEditText;
    private EditText actingExperienceEditText;
    private EditText representativeWorksEditText;
    private Spinner professionSpinner;
    private Button publishButton;

    private String currentPhotoPath;
    private String selectedImagePath;
    private String userName;
    private ImageUploadUtils imageUploadUtils;

    private boolean isAdmin = false; // 新增变量，用于标记是否为管理员

    private static final String TAG = "ReleaseActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 加载自定义布局
        setContentView(R.layout.activity_release);

        // 从 SharedPreferences 中读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        userName = sharedPreferences.getString("username", "");

        // 初始化视图组件
        backButton = findViewById(R.id.back_button);
        imageView = findViewById(R.id.imageView);
        nameEditText = findViewById(R.id.nameEditText);
        ageEditText = findViewById(R.id.ageEditText);
        birthDateEditText = findViewById(R.id.birthDateEditText);
        birthPlaceEditText = findViewById(R.id.birthPlaceEditText);
        nationalityEditText = findViewById(R.id.nationalityEditText);
        actingExperienceEditText = findViewById(R.id.actingExperienceEditText);
        representativeWorksEditText = findViewById(R.id.representativeWorksEditText);
        professionSpinner = findViewById(R.id.professionSpinner);
        publishButton = findViewById(R.id.publishButton);

        // 初始化 ImageUploadUtils
        imageUploadUtils = new ImageUploadUtils(this, imageView);

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理返回按钮点击事件，例如返回上一页
                finish();
            }
        });

        // 设置 ImageView 点击事件
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageUploadUtils.startImageUpload();
            }
        });

        // 获取用户信息并检查是否为管理员
        getUserInfo();

        // 设置发布按钮点击事件
        publishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String profession = professionSpinner.getSelectedItem().toString();
                // 检查是否是管理员或用户名以"MX"开头，并且分类不是“民”星
                if (!isAdmin && (userName == null ||!userName.startsWith("MX")) &&!"民之星".equals(profession)) {
                    Toast.makeText(StarActivity.this, "你权限不足(只能选择民之星分类)", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 进行输入校验
                if (validateInput()) {
                    // 获取用户输入的信息
                    String imageResource = selectedImagePath;
                    String name = nameEditText.getText().toString();
                    int age = Integer.parseInt(ageEditText.getText().toString());
                    String birthDate = birthDateEditText.getText().toString();
                    String birthPlace = birthPlaceEditText.getText().toString();
                    String nationality = nationalityEditText.getText().toString();
                    String actingExperience = actingExperienceEditText.getText().toString();
                    String representativeWorks = representativeWorksEditText.getText().toString();
                    // 创建 Star 对象
                    Star star = new Star(imageResource, name, age, birthDate, birthPlace, nationality, actingExperience, representativeWorks, profession);
                    star.setUserName(userName);// 使用读取到的用户名
                    // 发送 POST 请求保存到服务器
                    sendPostRequest(star);
                }
            }
        });

    }

    private void getUserInfo() {

        ApiStar apiStar = ApiClient.getApiStar();
        // 根据用户名获取用户信息
        Call<User> call = apiStar.getUserByUsername(userName);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    User user = response.body();
                    if (user != null) {
                        isAdmin = user.isAdmin();
                    }
                } else {
                    try {
                        String errorBody = response.errorBody().string();
                        Log.d(TAG, "Response error body: " + errorBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(StarActivity.this, "获取用户信息失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(StarActivity.this, "获取用户信息失败，网络请求出错: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        imageUploadUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        imageUploadUtils.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        selectedImagePath = imageUploadUtils.getSelectedImagePath();
    }

    private boolean validateInput() {
        // 校验姓名是否为空
        if (TextUtils.isEmpty(nameEditText.getText().toString())) {
            Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验年龄是否为空或是否为合法数字
        if (TextUtils.isEmpty(ageEditText.getText().toString())) {
            Toast.makeText(this, "年龄不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            int age = Integer.parseInt(ageEditText.getText().toString());
            if (age <= 0) {
                Toast.makeText(this, "年龄必须为正整数", Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "年龄必须为数字", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验出生日期是否为空
        if (TextUtils.isEmpty(birthDateEditText.getText().toString())) {
            Toast.makeText(this, "出生日期不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验出生地点是否为空
        if (TextUtils.isEmpty(birthPlaceEditText.getText().toString())) {
            Toast.makeText(this, "出生地点不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验国籍是否为空
        if (TextUtils.isEmpty(nationalityEditText.getText().toString())) {
            Toast.makeText(this, "国籍不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验演艺经历是否为空
        if (TextUtils.isEmpty(actingExperienceEditText.getText().toString())) {
            Toast.makeText(this, "演艺经历不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验代表作品是否为空
        if (TextUtils.isEmpty(representativeWorksEditText.getText().toString())) {
            Toast.makeText(this, "代表作品不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 校验职业是否为空或是否选择了“请选择分类”
        String profession = professionSpinner.getSelectedItem().toString();
        if (TextUtils.isEmpty(profession) || profession.equals("请选择分类")) {
            Toast.makeText(this, "分类不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void sendPostRequest(Star star) {
        ApiStar apiStar = ApiClient.getApiStar();
        Call<Star> call = apiStar.saveStar(star);
        call.enqueue(new Callback<Star>() {
            @Override
            public void onResponse(Call<Star> call, Response<Star> response) {
                int statusCode = response.code();
                Log.d(TAG, "Response status code: " + statusCode);
                if (response.isSuccessful()) {
                    Toast.makeText(StarActivity.this, "明星发布成功", Toast.LENGTH_SHORT).show();
                    // 发布成功后返回 HomeFragment
//                    getSupportFragmentManager().beginTransaction()
//                            .replace(R.id.fragment_container, new HomeFragment())
//                            .commit();
                    finish();
                } else {
                    try {
                        String errorBody = response.errorBody().string();
                        Log.d(TAG, "Response error body: " + errorBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(StarActivity.this, "明星发布失败，状态码: " + statusCode, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Star> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(StarActivity.this, "发布失败，网络请求出错: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}